const router = require('koa-router')();
const { sequelize } = require('../common/dbs')
var Sequelize = require('sequelize')
var Op = Sequelize.Op;

const messageModel = require("../models/message")
const messageinfo = messageModel(sequelize);


// 查询列表
router.get('/pageList', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;

        let reData = await messageinfo.findAll(
            {
                order: [  //排序 DESC ASC
                    ['created_at', 'DESC']
                ],
                limit: reqQuery.limit ? parseInt(reqQuery.limit) : 10,
                offset: reqQuery.page > 0 ? (parseInt(reqQuery.page) - 1) * 10 : 0,
            }
        );
        ctx.success(reData)
    } catch (err) {
        console.log(err)
        ctx.fail(0, err)
    }
})
// ---- 等待修改------------------------------------后台操作 需要验证登录的

// 查询列表
router.get('/list', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        let where = {}
        if (reqQuery.title) {
            where = {
                title: {
                    [Op.like]: `%${reqQuery['title']}%`
                }
            }
        }
        articleinfo.hasOne(classifyinfo, { foreignKey: 'id', sourceKey: 'cId' });
        let reData = await articleinfo.findAndCountAll(
            {
                where: where,
                // attributes: [Sequelize.col('classify_model.c_name'), 'id', 'content', 'views'],
                order: [  //排序 DESC ASC
                    ['created_at', 'DESC']
                ],
                limit: reqQuery.limit ? parseInt(reqQuery.limit) : 10,
                offset: reqQuery.page > 0 ? (parseInt(reqQuery.page) - 1) * 10 : 0,
                raw: true,
                include: [
                    {
                        attributes: [],
                        model: classifyinfo,
                    }
                ]
            }
        );

        ctx.success(reData)
    } catch (err) {
        console.log(err)
        ctx.fail(0, err)
    }
})
// 编辑或者添加
router.post('/editOrAdd', async (ctx) => {
    try {
        ctx
            .validateBody("content")
            .required("内容不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("title")
            .required("标题不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("desc")
            .required("简介不能为空")
            .isString()
            .trim()

        let reqBody = ctx.request.body;
        let requestData = null
        let msgType = '添加'
        let b = {
            content: reqBody.content,
            desc: reqBody.desc,
            title: reqBody.title,
            status: reqBody.status,
            cover: reqBody.cover,
            views: 0,
        }

        if (reqBody.id) {
            delete b.id
            // 编辑
            requestData = await articleinfo.update(b, {
                where: {
                    id: reqBody.id
                }
            })
            msgType = '修改'
        } else {
            // 新增
            requestData = await articleinfo.create(b)
        }
        if (requestData) {
            ctx.success(msgType + '成功')
        } else {
            ctx.fail(0, msgType + '失败')
        }

    } catch (err) {
        ctx.fail(0, err && err.message)
    }
})

// 删除
router.delete('/del/:id', async (ctx) => {
    try {
        if (!ctx.params.id) {
            ctx.fail(0, 'id不能为空')
        }
        let requestData = await articleinfo.destroy({
            where: {
                id: ctx.params.id
            }
        })
        if (requestData > 0) {
            ctx.success('删除成功')
        } else {
            ctx.fail(0, '文章已删除,或者不存在')
        }
    } catch (err) {
        ctx.fail(0, err)
    }
})




module.exports = router.routes();


